# -*- coding: utf-8 -*-
import osmnx as ox
import json
from shapely.geometry import Point, Polygon
import codecs
import xml.etree.ElementTree as xee
import numpy as np

taipei_map01 = "/home/dev-2/002_work_2023/05_Street_scene/SRC/map/taipei01"
taipei_map02 = "/home/dev-2/002_work_2023/05_Street_scene/SRC/map/taipei02"
taipei_json01 = 'taipei1_from_map.json'
taipei_json02 = 'taipei2_from_map.json'


# 读取xml格式的文件，摘取文件中所有坐标点数据，另存为json格式文件
def osmProcess(map_name, json_name):
    # 读取文件
    domTree = xee.parse(map_name)
    # 获得所有节点的内容
    root = domTree.getroot()
    # 获得所有"node"节点列表
    nodes = root.findall("node")
    # print(type(nodes))
    # datas=[]

    json_file = codecs.open(json_name, 'w+', encoding='UTF-8')
    json_file.write('[\n')
    datas = []
    for node in nodes:
        # 当前节点的经纬度和ID
        data = dict()
        data["lat"] = node.get("lat")
        data["lon"] = node.get("lon")
        datas.append(data)
        # print(data)
        # print(datas)
        item_json = json.dumps(data, ensure_ascii=False)
        json_file.write('\t' + item_json + ',\n')

    json_file.write(']\n')
    json_file.close()


# 读取xml格式的文件，摘取文件中所有坐标点数据
def osm_Process(map_name):
    # 读取文件
    domTree = xee.parse(map_name)
    # 获得所有节点的内容
    root = domTree.getroot()
    # 获得所有"node"节点列表
    nodes = root.findall("node")
    print(f"type(nodes):{type(nodes)}")
    datas = [[node.get("lon"), node.get("lat")] for node in nodes]
    # 返回文件中所有坐标点数据
    return datas


# 判断坐标点是否属于指定范围/区域
def taipei_contains():
    # 指定城市
    place_name = "taipei"

    # 下载该市的图形数据，并将其转换为Polygon对象：
    city_polygon = ox.geocode_to_gdf(place_name).iloc[0]['geometry']

    # 将城市图形数据转换为Polygon对象
    city_polygon = city_polygon.buffer(0)

    # 从文件中读取坐标点
    datas02 = osm_Process(taipei_map01)

    # 创建一个Point对象表示待判断的坐标点，并判断该点是否在城市区域内：
    pop_index = []
    for i in range(len(datas02)):
        lon = float(datas02[i][0])
        lat = float(datas02[i][1])

        # 创建待判断的Point对象
        # point = Point(-73.9569, 40.7681)  # 以纽约市的中心为例
        point = Point(lon, lat)

        # 判断点是否在城市区域内
        if city_polygon.contains(point):
            pass
        # print("该点位于%s内。" % place_name)
        else:
            pop_index.append(i)
        # print("该点不位于%s内。" % place_name)
    print(f"len(datas02):{len(datas02)} \n len(pop_index):{len(pop_index)}\n{pop_index[:5]}\n")
    pop_index.reverse()

    datas03 = [datas02.pop(i) for i in pop_index]
    # datas03 = np.delete(np.array(datas02), pop_index).tolist()
    print(f"len(datas02):{len(datas02)} \n\nlen(datas03):{len(datas03)} {datas03[:3]}\n")

    # 坐标点写入新文件
    write_to_json(datas02, taipei_json01)


def write_to_json(data, name):
    tmp_data = {}
    tmp_data["data"] = data
    tmp_json = json.dumps(tmp_data, ensure_ascii=False)
    with open(name, 'w+') as f:
        f.write(tmp_json)


def ReadJsonFromTaipei():
    with open(taipei_json01, encoding='utf-8-sig', errors='ignore') as f:
        Datas01 = json.load(f, strict=False)
        # print(len(Datas01),type(Datas01))
        f.close()

    with open(taipei_json02, encoding='utf-8-sig', errors='ignore') as f:
        Datas = json.load(f, strict=False)
        # print(len(Datas),type(Datas))
        f.close()

    # tmp_data = [["121.55051","25.10033"]] + Datas01["data"] + Datas["data"]
    # 添加指定坐标到坐标集合中
    # 指定坐标可从google街景地图中选取
    tmp_data = [["121.5576898", "25.039797"]] + Datas01["data"] + Datas["data"]  # "taipei02.json"
    print(len(tmp_data))
    write_to_json(tmp_data, "taipei02.json")


if __name__ == "__main__":
    # taipei_contains()
    # osm_Process(taipei_map02,taipei_json02)
    ReadJsonFromTaipei()
